﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Security.Cryptography;
using System.Threading;
using System.Net;

using AutoUploadTPlan.utils;
using MultipartFormData;



namespace AutoUploadTPlan
{
    

    public partial class MainForm : Form
    {
        static object locker = new object();
        static object locker_allFile = new object();
        static object locker_listView = new object();
        private Dictionary<string, TPFileInfo> allFiles = new Dictionary<string, TPFileInfo>();
        private SetTimeForm setTimeForm = new SetTimeForm();
        private string user = "2013111004";
        private string pwd = "lightning123";
        private string loginUrl = "http://192.168.11.166:8090";
        public MainForm()
        {
            InitializeComponent();
            this.listView_result.Columns.Add("编号", 50, HorizontalAlignment.Left);
            this.listView_result.Columns.Add("文件名称", 200, HorizontalAlignment.Left);
            this.listView_result.Columns.Add("上传周次", 120, HorizontalAlignment.Left);
            this.listView_result.Columns.Add("状态", 160, HorizontalAlignment.Left);

            this.listView_result.View = System.Windows.Forms.View.Details;
            //this.listView_result.CheckBoxes = true;
            this.listView_result.AllowDrop = true;

            this.setTimeForm.VisibleChanged += new System.EventHandler(this.setTimeForm_VisibleChanged);
            
            
        }

        private void MainForm_Load(object sender, EventArgs e)
        {

        }
        private void setTimeForm_VisibleChanged(object sender, EventArgs e)
        {
            
            if (this.setTimeForm.Visible == false)
            {
                //MessageBox.Show(this.setTimeForm.getWeek());
                string week = this.setTimeForm.getWeek();
                this.listView_result.FocusedItem.SubItems[2].Text = string.Format("第{0}周上传",week);
                this.listView_result.FocusedItem.SubItems[3].Text = string.Format("将于第{0}周上传", week);
                
                string fname = this.listView_result.FocusedItem.SubItems[1].Text ;
                string key = this.getMD5(fname);
                TPFileInfo tpfile = null;
                lock (locker_allFile)
                {
                    if (this.allFiles.ContainsKey(key))
                    {
                        tpfile = this.allFiles[key];
                        tpfile.Date = week;
                    }
                    else
                    {
                        this.SetText("ERROR: "+fname+" not in allfiles, something is wrong...");
                    }
                }
                if (tpfile != null)
                {
                    this.uploadFile2Server(tpfile);
                }
            }
        }
        private bool uploadFile2Server(TPFileInfo tpfile)
        {
            try
            {
                Thread t = new Thread(uploadFile);
                t.Start(tpfile);
                return true;
            }
            catch (Exception ex)
            {
                this.SetText("Exception: " + ex.Message);
                return false;
            }
        }
        private void uploadFile(object obj)
        {
            TPFileInfo tpfile = (TPFileInfo)obj;
            HttpItem httpItem = new HttpItem();
            httpItem.PostDataType = PostDataType.FilePath;

            //要Post的数据
            string postfile = tpfile.Path;
            string week = tpfile.Date;
            string fname = tpfile.Name;

            string url = string.Format("{0}/upload",this.loginUrl);
            //string url = this.loginUrl;
            Dictionary<string, string> values = new Dictionary<string, string>();
            values.Add("week",tpfile.Date);
            values.Add("fname",tpfile.Name);
            values.Add("user",this.user);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            CustomFile cf = new CustomFile("file", tpfile.Path, "application/octet-stream");
            List<CustomFile> filesList = new List<CustomFile>();
            filesList.Add(cf);

            HttpClient.BuildStreamRequest(request, values, filesList);

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            string status = response.StatusCode.ToString();
            
        }
        private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }
        private bool importFile(string fileName)
        {
            try
            {
                if (!File.Exists(fileName))
                {
                    MessageBox.Show("文件:{0}不存在");
                    return false ;
                }
                //this.SetText(string.Format("添加{}到列表中",fileName));
                TPFileInfo tpfile = new TPFileInfo();
                tpfile.Name = Path.GetFileName(fileName);
                tpfile.Path = fileName;
                tpfile.Status = 0 ;
                tpfile.Date = "";
                string key = this.getMD5(tpfile.Name);
                bool needUpload = false;
                lock (locker_allFile)
                {
                    if (!this.allFiles.ContainsKey(key))
                    {
                        allFiles.Add(key, tpfile);
                        this.updateListView(tpfile);
                        needUpload = true;
                    }
                    else 
                    {//文件名已经存在，是替换？
                        MessageBox.Show("文件："+tpfile.Name+"已上传，如需重传，请先右击删除");
                        //删除文件的时候，要判断是不是已经上传到课件系统里，如果已经上传，要删除
                        //上传到代理服务器的可以覆盖
                        //修改上传时间的，要在代理服务器上删除，然后重新上传
                    }
                }
                if (needUpload)
                {
                    uploadFile(fileName);
                }

                return true ;
            }
            catch (Exception ex)
            {
                MessageBox.Show("IMPORTFILE:" + ex.Message);
                return false ;
            }
        }
        private bool uploadFile(string fileName)
        {

            return true;
        }
        private void updateListView(TPFileInfo tpfile)
        {
            int count = this.listView_result.Items.Count;
            ListViewItem lvi = new ListViewItem();
            lvi.Checked = true;
            lvi.Text = (count + 1).ToString();

            string key = this.getMD5(tpfile.Name);

            if (this.allFiles.ContainsKey(key))
            {
                lvi.SubItems.Add(tpfile.Name);
                lvi.SubItems.Add(tpfile.Date);
                lvi.SubItems.Add(this.getTPFileStatusStr(tpfile.Status));
                //this.listView_result.Items.Add(lvi);//进行查找更新，不能直接添加???
                this.SetListView(lvi);
            }
            else
            {
                this.SetText("数据不一致，请连续管理员");
            }
        }
        private void SetListView(ListViewItem lvi,bool rewrite=true)
        {
            try
            {
                this.Invoke((EventHandler)delegate
                {
                    lock (locker_listView)
                    {
                        ListViewItem lvi_tmp = this.listView_result.FindItemWithText(lvi.SubItems[1].Text);

                        this.listView_result.BeginUpdate();
                        if (lvi_tmp != null)
                        {
                            lvi_tmp.SubItems[2].Text = lvi.SubItems[2].Text;
                            lvi_tmp.SubItems[3].Text = lvi.SubItems[3].Text;
                        }
                        else
                        {
                            lvi.Checked = true;
                            this.listView_result.Items.Add(lvi);//进行查找更新，不能直接添加
                        }

                        this.listView_result.EndUpdate();

                    }
                });
            }
            catch (Exception ex)
            {
                MessageBox.Show("SETLISTVIEW：" + ex.Message);
            }
        }
        private string getTPFileStatusStr(int status)
        {
            string statusStr = "";
            switch (status)
            {
                case 0:
                    statusStr = "双击设置上传时间";//"未上传";
                    break;
                case 1:
                    statusStr = "等待上传";
                    break;
                case 2:
                    statusStr = "已经上传";
                    break;
            }
            return statusStr;
        }
        private void SetText(string text)
        {
            try
            {
                this.Invoke((EventHandler)delegate
                {
                    lock (locker)
                    {
                        this.tb_status.AppendText(text + "\r\n");
                    }
                });
            }
            catch
            { }
        }

        private void listView_result_DragEnter(object sender, DragEventArgs e)
        {
            this.SetText("DragEnter");
            try
            {
                e.Effect = DragDropEffects.Copy;
                String[] str_Drop = (String[])e.Data.GetData(DataFormats.FileDrop, true);//必须用字符串数组
                foreach(string fileName in str_Drop)
                {
                    //this.SetText(fileName);
                    this.SetText(Path.GetFileName(fileName));
                    this.importFile(fileName);
                }
                //string fileName = str_Drop[0];
                //int count = importCookie(fileName);
                //MessageBox.Show("DRAGENTER:" + fileName);
            }
            catch (Exception ex)
            {
                MessageBox.Show("DRAGENTER:" + ex.Message);
            }
        }
        private string getMD5(string str)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] fromData = System.Text.Encoding.Unicode.GetBytes(str);
            byte[] targetData = md5.ComputeHash(fromData);
            string byte2String = null;

            for (int i = 0; i < targetData.Length; i++)
            {
                byte2String += targetData[i].ToString("x");
            }

            return byte2String;
        }

        private void listView_result_DoubleClick(object sender, EventArgs e)
        {

            this.SetText(this.listView_result.FocusedItem.SubItems[1].Text);
        }

        private void listView_result_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
        
        private void listView_result_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.listView_result.Focus();
            ListViewHitTestInfo info = this.listView_result.HitTest(e.X, e.Y);
            ListViewItem item = info.Item;

            if (item != null)
            {
                //MessageBox.Show("The selected Item Name is: " + item.SubItems[1].Text);
                this.setTimeForm.Visible = true;
                this.setTimeForm.Show();
                
            }
            else
            {
                this.listView_result.SelectedItems.Clear();
                MessageBox.Show("No Item is selected");
            }
        }
    }
}
